package com.common.resolve;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @Description:
 * @Date: 2025/7/7 11:49
 */
@Component
public class ApplicationJsonContentTypeResolve implements ContentTypeResolve{
    @Override
    public ContentType contentType() {
        return ContentType.JSON;
    }

    @Override
    public JSONObject resolve(ServletRequest servletRequest, ServletResponse servletResponse) {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
             ServletInputStream inputStream = servletRequest.getInputStream()){
            IoUtil.copy(inputStream, outputStream);
            return JSONUtil.parseObj(IoUtil.toStr(outputStream, StandardCharsets.UTF_8));
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }
}
